#ifndef CUSTOMDELEGATE_H
#define CUSTOMDELEGATE_H
#include <QStyledItemDelegate>
#include <QPainter>
#include <QDebug>
#include <QApplication>

class CustomDelegate : public QStyledItemDelegate
{
    Q_OBJECT
public:
    CustomDelegate();
public:
    void paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const override {
        // 绘制图片，这里需要先获取图片数据
        if (option.state.testFlag(QStyle::State_Selected)) {
            QRect rect = option.rect;//控件默认的矩形大小
            rect.setWidth(rect.width()/2);//把宽度设置为一半
            painter->setBrush(Qt::cyan);

            // 如果项被选中，绘制选中背景
            painter->fillRect(rect, painter->brush());
        }

         QPixmap pixmap;
//         index.data()可以获得当前所在的格子的文本（图片名）
//         .toString()是把万能类型转为字符串类型
         bool ret = pixmap.load(index.data().toString());
         if(ret == false)
         {
             qDebug()<<index.data().toString();//打印出加载失败的图片名
             //qDebug()<<"加载图片失败";
             return;
         }
//        option.rect是格子的矩形
         QRect rect1 = option.rect;
         rect1.setWidth(rect1.width()/3);
         rect1.setHeight(rect1.width());
         painter->drawPixmap(rect1, pixmap);



         // 绘制文本
//         painter->drawText(option.rect, Qt::AlignCenter, index.data().toString());

    }

};

#endif // CUSTOMDELEGATE_H
